<?php
/**
 * Author: liqinglin
 * CreateTime: 2019-1-22 9:22
 * description:
 */

namespace app\admin\controller;


use think\Db;
use think\Request;
use think\Console;
use app\admin\model\ServiceType;
use Im\Yunxinapi;
use tp_master\Input;

class User extends Base
{
    /**
     * 用户列表
     * @author 274805539@qq.com
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $search['user_mobile'] = input('user_mobile');
        $search['user_email'] = input('user_email');
        $search['user_type'] = input('user_type');
        $search['user_nickname'] = input('user_nickname');
        $search['is_test'] = input('is_test');
        $query = DB::table('cn_user_info c_ui')
            ->join('cn_user_base c_ub', 'c_ui.user_id=c_ub.user_id', 'left')
            ->join('ucenter_user_info uc_ui', 'c_ui.user_id = uc_ui.user_id', 'left')
            ->field('c_ui.user_id,c_ui.im_user_token,c_ui.user_name,c_ui.user_nickname,c_ui.user_mobile,c_ui.user_email,c_ub.user_type,c_ui.user_regtime,c_ui.user_logo,c_ui.user_last_lng,c_ui.user_last_lat,uc_ui.is_test');
        if ($search['user_type']) {
            $query = $query->where('c_ub.user_type', $search['user_type']);
        }


        if (strlen($search['is_test']) == 1 && in_array($search['is_test'], [0, 1])) {
            $query = $query->where('uc_ui.is_test', $search['is_test']);
        }

        if ($search['user_mobile']) {
            $query = $query->where(" c_ui.user_mobile LIKE '%{$search['user_mobile']}%'");
        }
        if ($search['user_email']) {
            $query = $query->where(" c_ui.user_email LIKE '%{$search['user_email']}%'");
        }
        if ($search['user_nickname']) {
            $query = $query->where(" c_ui.user_nickname LIKE '%{$search['user_nickname']}%'");
        }

        $query = $query->order('c_ub.user_id', 'desc');
        $data = $query->paginate(10)->appends($search);
        return view('/user/list', compact('data', 'search'));

    }

    /**
     * 批量增加用户,展示页
     * @return \think\response\View
     */
    public function add()
    {
        if (Request::instance()->isGet()) {
            $data['service_all_types'] = ServiceType::getAllType();
            return view('/user/add', compact('data'));
        } else {

        }
    }


    public function editUserName()
    {
        if (Request::instance()->isGet()) {
            $data=Db::name('cn_user_info')->where('user_id',input('user_id'))->find();
            return view('/user/editUserName', compact('data'));
        } else {
            $user_id=input('user_id');
            $user_nickname=input('user_nickname');
            Db::name('cn_user_info')->where('user_id',$user_id)->update(['user_nickname'=>$user_nickname]);
            Db::name('cn_user_friend')->where('friend_id',$user_id)->update(['friend_nickname'=>$user_nickname]);
            $user_info=Db::name('cn_user_info')->where('user_id',$user_id)->find();
            $Yx=new Yunxinapi();
            $yx_res=$Yx->updateUinfo($user_info['user_name'], $user_nickname);
            return json(array('status' => 200, 'msg' => lang('成功'), 'data' => ''));
        }
    }

    /**
     * 进行调用command 进行执行批量生成用户
     * @return \think\response\Json
     */
    public function SendUser()
    {
        $user_type = input('user_type');//（1商家，2买家,3,服务商）
        $number = input('number');
        $email_ = input('email');
        $longLat = input('longLat');
        $lan_lng = input('lng');
        $user_nickname = input('user_nickname');
        $res = explode(',', $lan_lng);
        $lat = $res[0];
        $lng = $res[1];
        if (empty($user_type) || empty($email_) || empty($number)) {
            return json(array('status' => 400, 'msg' => lang('提交数据不能为空')));
        }
        /*  $parameters = [
              'user_type' => $user_type,
              'number' => $number,
              'email' => $email_,
              'longLat' => $longLat,
              'lat' => $lat,
              'lng' => $lng,
              'user_nickname' => $user_nickname
          ];*/

        //$user_type = trim($input->getArgument('user_type'));
        //$number = trim($input->getArgument('number'));
        //$email_ = trim($input->getArgument('email'));
        // $longLat = trim($input->getArgument('longLat'));
        //$lat = trim($input->getArgument('lat'));
        //$lng = trim($input->getArgument('lng'));
        //$user_nickname = trim($input->getArgument('user_nickname'));
        $user_type = $user_type ?: 1;
        $number = $number ?: 10;
        $email_ = $email_ ?: 'cnsellers_';
        // 1、服务商 2、供应商 3、采购商
        $user_role = ($user_type == 1) ? 2 : (($user_type == 2) ? 3 : (($user_type == 3) ? 1 : 0));
        for ($i = 0; $i < $number; $i++) {
            //自定义一些数据
            $user_id = time();
            //********************循环开始
            $type = 2;         // '1:中国区用户  2:非中国区用户';
            $password = md5('123456');     // '密码';
            $user_logo = $this->getRandAvatars(); //随机头像
            $email = $email_ . $user_id . '@163.com';
            $mobile = '';
            $countrycode = 86;
            //$user_nickname = getUserNikeName(); //用户随机昵称
            //$user_nickname = getCompanyName($longLat); //用户随机昵称
            $user_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
            $environment_prefix_user_name = $user_id;

            //开启事务
            DB::startTrans();
            try {
                //ucenter库 --- start
                $ucenter_user_bind_connect_data_email = array(
                    'bind_id' => 'email_' . $email,
                    'bind_type' => 11,
                    'user_id' => $user_id,
                    'bind_time' => date("Y-m-d H:i", $user_id)
                );
                DB::table('ucenter_user_bind_connect')->insert($ucenter_user_bind_connect_data_email);

                $ucenter_user_info_detail_data = array(
                    'user_name' => config('environment_prefix_user_name') . $user_id,
                    'user_mobile_county_code' => $countrycode,
                    'user_mobile' => $mobile,
                    'user_email' => $email,
                    'user_mobile_verify' => 0,
                    'user_email_verify' => 1
                );
                DB::table('ucenter_user_info_detail')->insert($ucenter_user_info_detail_data);

                $ucenter_user_info_data = array(
                    'user_id' => $user_id,
                    'user_name' => config('environment_prefix_user_name') . $user_id,
                    'password' => $password,
                    'action_time' => $user_id,
                    'action_ip' => $user_ip,
                    'session_id' => uniqid(),
                    'user_type' => 2,
                    'is_test' => 1,
                    'user_country_type' => $type
                );
                Db::table('ucenter_user_info')->insert($ucenter_user_info_data);
                //ucenter库 --- end


                $lng_lat = getLngLat($longLat);//获取随机经纬度
                $rand_index = rand(0, 20);
                //shop库 --- start
                $cn_user_info_data = array(
                    'user_id' => $user_id,
                    'user_nickname' => $user_nickname ? $user_nickname : $environment_prefix_user_name,
                    'user_mobile' => $mobile,
                    'user_mobile_county_code' => $countrycode,
                    'user_email' => $email,
                    'user_name' => config('environment_prefix_user_name') . $user_id,
                    'user_regtime' => date("Y-m-d H:i", time()),
                    'user_role' => $user_role,
                    'user_logo' => $user_logo,
                    'user_last_lng' => $lat,//经度
                    'user_last_lat' => $lng,//维度
                );
                Db::table('cn_user_info')->insert($cn_user_info_data);

                $cn_user_base_data = array(
                    'user_id' => $user_id,
                    'user_account' => config('environment_prefix_user_name') . $user_id,
                    'user_key' => 'ttt',
                    'user_login_times' => 1,
                    'user_login_time' => date("Y-m-d H:i", time()),
                    'user_login_ip' => $user_ip,
                    'user_type' => $user_type,
                    'seller_type' => 0
                );
                Db::table('cn_user_base')->insert($cn_user_base_data);
                if ($user_type == 3) {
                    //shop库 --- end
                    $service_id = getUniqueId('s_');
                    Db::table('cn_service_base')->insert(['user_id' => $user_id, 'service_id' => $service_id]);
                    Db::table('cn_service_company')->insert(['service_id' => $service_id]);
                }

                Db::commit();
                //注册云信账号
                $Yx = new Yunxinapi();
                $result = $Yx->createUserId($cn_user_info_data['user_name'], $cn_user_info_data['user_nickname'],
                    '');
                DB::name('cn_user_info')->where('user_id', $user_id)
                    ->update(['im_user_token' => $result['info']['token']]);
                //*******************注册完成

            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }

            if ($number != 1) {
                sleep(1);//防止生成的id冲突,延迟1秒后循环
            }

            //********************循环截止
        }
        //批量生成用户在后台进行运行
        //Console::call('User', $parameters);
        return json(array('status' => 200, 'msg' => lang('成功'), 'data' => ''));
    }


    /**
     * 注册用户统计
     * @author 274805539@qq.com
     * @return \think\response\View
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function LookRegister()
    {
        $start_time = input('start_time');
        $end_time = input('end_time');
        $download = input('download');
        // $download = 1;
        $query = DB::name('cn_user_info')
            ->field("DATE_FORMAT( user_active_time, \"%Y-%m-%d\" ) AS time, 
COUNT(user_id) AS total");
        if (empty($start_time) && empty($end_time)) {
            $time = date('Y-m', time());
            $query = $query->where("user_active_time LIKE '%{$time}%' ");
        } else {
            $sql = $this->getWhereSql($start_time, $end_time);
            if ($sql) {
                $query = $query->where($sql);
            } else {
                $time = date('Y-m', time());
                $query = $query->where("user_active_time LIKE '%{$time}%' ");
            }
        }
        $data = $query->group('time')
            ->select();
        $number = DB::name('cn_user_info')->count();
        if ($download == 1) {
            $this->downLoadExcel($data);
            die;
        }
        if (empty($search['start_time']) && empty($search['end_time'])) {
            $search['start_time'] = date('Y-m', time()) . '-01';
            $search['end_time'] = date('Y-m', time()) . '-' . cal_days_in_month(CAL_GREGORIAN, date('m', time()), date('Y', time()));
        } else {
            $search['start_time'] = $start_time;
            $search['end_time'] = $end_time;
        }

        return view('/user/register_count', compact('data', 'search', 'number'));
    }


    /**
     * 获取搜索sql语句
     * @author 274805539@qq.com
     * @param $start_time
     * @param $end_time
     * @return string
     */
    public function getWhereSql($start_time, $end_time)
    {
        //$start_time = '2019-10-01';
        //$end_time = '2019-10-10';
        $new_time_arr = [];
        //$last_time = substr($end_time, 0, 7);

        $start = new \DateTime($start_time);
        $end = new \DateTime($end_time);
        $interval = \DateInterval::createFromDateString('1 day');
        $period = new \DatePeriod($start, $interval, $end);
        foreach ($period as $dt) {
            $new_time_arr[] = $dt->format("Y-m-d");
        }

        if ($new_time_arr) {
            if ($new_time_arr[count($new_time_arr) - 1] != $end_time) {
                $new_time_arr[] = $end_time;
            }
        }
        $where = " ";
        if ($new_time_arr) {
            foreach ($new_time_arr as $key => $value) {
                if ($key == 0) {
                    $where .= " user_active_time LIKE '%{$value}%' ";
                } else {
                    $where .= " OR  user_active_time LIKE '%{$value}%' ";
                }
            }
        };
        return $where;
    }


    /**
     * 下载excel
     * @author 274805539@qq.com
     * @param $data
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function downLoadExcel($data)
    {
        import('PHPExcel.PHPExcel', EXTEND_PATH);
        header("Content-Type:text/html;charset=utf-8");
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);

        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        //表头数组
        $tableheader = array('日期', '注册人数',);

        $excel = new \PHPExcel();
        //填充表头信息'
        $excel->getActiveSheet()->setTitle('用户注册统计');
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        $data = json_decode(json_encode($data), true);
        //填充表格信息
        $objSheet = $excel->getActiveSheet();
        $objSheet->getColumnDimension('A')->setWidth(50);
        $objSheet->getColumnDimension('B')->setWidth(50);
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key => $value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$value");
                $j++;
            }
        }
        //创建Excel输入对象
        ob_end_clean();
        $objWriter = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        //多浏览器下兼容中文标题
        $fileName = '用户统计' . date("Y-m-d-h-i-s", time());
        $encoded_filename = urlencode($fileName);
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '.csv"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '.csv"');
        }
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    public function getRandAvatars()
    {
        $curl = new  \tp_tools\Curl;
        $path_row = ROOT_PATH . 'public' . DS . 'avatars300' . DS . sprintf("%'04d", rand(1, 300)) . '.jpg';
        $upfile = ['upfile' => new \CURLFile($path_row, 'image/jpeg')];
        $remote_url = config('remote_url');
        $remote = $curl->post($remote_url, $upfile, true);
        if ($remote) {
            $remote = json_decode($remote, true);
            if ($remote['ststus'] == 200) {
                if (isset($remote['data']['url'])) {
                    return $remote['data']['url'];
                } else {
                    return '';
                }
            }
        } else {
            return '';
        }

    }

}